package cn.cxyxj.study06.email;

import cn.cxyxj.study06.entity.SysUser;
import cn.cxyxj.study06.mapper.SysRoleMapper;
import cn.cxyxj.study06.mapper.SysUserMapper;
import cn.cxyxj.study06.model.SysUserDetails;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.ibatis.annotations.Select;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author cxyxj
 */
@Service
public class EmailVerificationCodeService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysRoleMapper sysRoleMapper;

    UserDetails loadUserByEmail(String email) {

        SysUser user = sysUserMapper.selectOne(new LambdaQueryWrapper<SysUser>().eq(SysUser::getEmail, email));
        if(Objects.isNull(user)){
            return null;
        }
        // 获得用户角色信息
        List<String> roles = sysRoleMapper.selectByRoleId(user.getRoleId());
        // 构建 SimpleGrantedAuthority 对象
        List<SimpleGrantedAuthority> authorities = roles.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
        return new SysUserDetails(user, authorities);
    }
}
